package com.foreknow.elmboot.service.impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.DeliveryAddress;
import com.foreknow.elmboot.po.OrderDetailEts;
import com.foreknow.elmboot.po.OrderIdCart;
import com.foreknow.elmboot.service.OrderService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartMapper cartMapper;

    @Override
    public List<DeliveryAddress> readAddress(Integer userId) throws Exception {
        return orderMapper.readAddress(userId);
    }

    @Override
    @Transactional
    public int saveOrders(OrderIdCart orderIdCart) throws Exception {
        List<OrderDetailEts> orderDetailEtsList = new ArrayList();
        List<Cart> list = cartMapper.listCart(orderIdCart.getBusinessId(),orderIdCart.getUserId());
        double cartSum = list.get(0).getBusiness().getDeliveryPrice();
        //将OrderDetailEts数据提取并保存
        for (Cart i:list){
            cartSum += (i.getFood().getFoodPrice()*i.getQuantity());
            OrderDetailEts orderDetailEts = new OrderDetailEts();
            orderDetailEts.setCartId(i.getCartId());
            orderDetailEts.setFoodId(i.getFoodId());
            orderDetailEts.setNumber(i.getQuantity());
            orderDetailEtsList.add(orderDetailEts);
        }
        orderIdCart.setOrderTotal(cartSum);
        //创建orders订单
        if (orderMapper.saveOrders(orderIdCart)==0){
            System.out.println("添加数据有误！");
            return 0;
        }
        //创建orderDetailet订单
        for (OrderDetailEts o : orderDetailEtsList){
            if(orderMapper.saveOrderDetailet(orderIdCart.getOrderId(),o.getFoodId(),o.getNumber())==0){
                System.out.println("saveOrderDetailet方法有误！");
                return 0;
            }
        }
        //删除对应购物车内数据
        for (OrderDetailEts d : orderDetailEtsList){
            if (cartMapper.deleteCart(d.getCartId())==0){
                System.out.println("deleteCart方法有问题！");
                return 0;
            }
        }
        return 1;
    }
}
